1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
use super::*;

/// The empty consistent constraint set
pub const NO_CONSTRAINTS_CONSISTENT: Consistent = Consistent(None);

/// The empty constraint set
pub const NO_CONSTRAINTS: Constraints = Constraints::Consistent(NO_CONSTRAINTS_CONSISTENT);

/// A consistent constraint set
#[derive(Clone, Eq, Default)]
pub struct Consistent(Option<HashMap<Option<ValId>, Constraint>>);

impl Consistent {
    /// Create a new, empty consistent constraint-set
    #[inline]
    pub fn new() -> Consistent {
        NO_CONSTRAINTS_CONSISTENT
    }
    /// Clear this constraint set
    #[inline]
    pub fn clear(&mut self) {
        if let Some(map) = &mut self.0 {
            //TODO: iterative clear?
            map.clear()
        }
    }
    /// Get the underlying map of this constraint-set
    #[inline]
    fn get_map(&mut self) -> &mut HashMap<Option<ValId>, Constraint> {
        self.0.get_or_insert_with(HashMap::default)
    }
    /// Get the underlying constraint of a symbol
    #[inline]
    fn get_constraint(&mut self, symbol: Option<ValId>) -> &mut Constraint {
        self.get_map()
            .entry(symbol)
            .or_insert_with(Constraint::default)
    }
    /// Get the constraint of a symbol, if any
    pub fn constraint(&self, symbol: &Option<ValId>) -> &Constraint {
        self.0
            .as_ref()
            .map(|map| map.get(symbol))
            .flatten()
            .unwrap_or(&NO_CONSTRAINT)
    }
    /// Get the values which come before or at the same time as this value, according to this constraint-set
    pub fn prev(&self, value: &Option<ValId>) -> impl Iterator<Item = (&ValId, Relationship)> {
        self.constraint(value)
            .iter()
            .filter_map(|(value, relationship)| match relationship.variance() {
                Covariant | Invariant => value.as_ref().map(|value| (value, *relationship)),
                _ => None,
            })
    }
    /// Get the strict dependencies of this value, according to this constraint set
    pub fn deps(&self, value: &Option<ValId>) -> impl Iterator<Item = (&ValId, Usage)> {
        self.constraint(value)
            .iter()
            .filter_map(|(value, relationship)| {
                match (relationship.variance(), relationship.strict()) {
                    (Covariant, true) => value.as_ref().map(|value| (value, relationship.usage())),
                    _ => None,
                }
            })
    }
    /// Rebase-union this constraint set with another
    ///
    /// Leaves this set in an undetermined but valid state in case of contradiction
    pub fn rebase_union(
        &mut self,
        other: &Consistent,
        base: Option<&ValId>,
        separating: bool,
    ) -> Result<bool, Error> {
        let mut change = false;
        for (value, constraint) in other.iter() {
            if !constraint.is_empty() {
                change |= self.get_constraint(value.clone()).rebase_union(
                    &constraint,
                    base,
                    separating,
                )?;
            }
        }
        Ok(change)
    }
    /// Union this constraint set with another
    ///
    /// Leaves this set in an undetermined but valid state in case of contradiction
    #[inline]
    pub fn union(&mut self, other: &Consistent, separating: bool) -> Result<bool, Error> {
        self.rebase_union(other, None, separating)
    }
    /// Require a constraint between two values, returning an error on inconsistency
    pub fn require(
        &mut self,
        left: Option<ValId>,
        right: Option<ValId>,
        relationship: Relationship,
        separating: bool,
    ) -> Result<bool, Error> {
        if relationship.is_contradiction() {
            return Err(Error::Contradiction);
        }
        if left.as_ref().map(ValId::is_const).unwrap_or_default() {
            return Ok(false);
        }
        if right.as_ref().map(ValId::is_const).unwrap_or_default() {
            return Ok(false);
        }
        if left == right {
            return if relationship.strict() {
                Err(Error::Cycle)
            } else {
                Ok(false)
            };
        }
        let change =
            self.get_constraint(left.clone())
                .require(right.clone(), relationship, separating)?;
        if change {
            self.get_constraint(right)
                .require(left, relationship.flip(), separating)
                .expect("One sided contradictions should not be possible!");
        }
        Ok(change)
    }
    /// Require a rebased constraint on a value, returning an error on inconsistency
    pub fn rebase_require(
        &mut self,
        value: Option<ValId>,
        constraint: &Constraint,
        base: Option<&ValId>,
        separating: bool,
    ) -> Result<bool, Error> {
        self.get_constraint(value)
            .rebase_union(constraint, base, separating)
    }
    /// Iterate over this constraint set
    pub fn iter(&self) -> impl Iterator<Item = (&Option<ValId>, &Constraint)> {
        self.0
            .iter()
            .flat_map(|map| map.iter().filter(|(_, constraint)| !constraint.is_empty()))
    }
    /// Require a set of values be equivalent
    pub fn require_equivalence<'a, I>(&mut self, scc: I) -> Result<bool, Error>
    where
        I: Clone + Iterator<Item = &'a ValId>,
    {
        let mut change = false;
        for x in scc.clone() {
            for y in scc.clone() {
                if x.as_ptr() != y.as_ptr() {
                    change |=
                        self.require(Some(x.clone()), Some(y.clone()), Relationship::EQ, true)?;
                }
            }
        }
        Ok(change)
    }
    /// Perform a cycle check on this constraint set
    pub fn cycle_check<P>(&mut self, result: &ValId, dep_filter: P) -> Result<bool, Error>
    where
        P: Clone + FnMut((&ValId, Relationship)) -> Option<&ValId>,
    {
        use pathfinding::directed::strongly_connected_components::strongly_connected_components_from;
        let sccs = strongly_connected_components_from(result, |value| {
            let value = Some(value.clone());
            let prev = self.prev(&value).filter_map(dep_filter.clone());
            prev.cloned()
        });
        let mut change = false;
        for scc in sccs {
            change |= self.require_equivalence(scc.iter())?;
        }
        Ok(change)
    }
    /// Get the code array of this constraint-set
    pub fn code_array(&self) -> SmallVec<[u64; 10]> {
        let mut key_codes: SmallVec<[u64; 10]> = self
            .iter()
            .map(|(value, constraint)| {
                value.as_ref().map(ValId::code).unwrap_or_default() ^ constraint.code()
            })
            .collect();
        key_codes.sort_unstable();
        key_codes
    }
    /// Get the usual hasher used for consistent constraint sets
    pub fn get_hasher(&self) -> AHasher {
        AHasher::new_with_keys(3243, 5634)
    }
    /// Get a code for this consistent constraint set
    pub fn code(&self) -> u64 {
        let mut hasher = self.get_hasher();
        self.hash(&mut hasher);
        hasher.finish()
    }
    /// Compute the free variable set of this constraint set
    pub fn fv(&self) -> SymbolSet {
        let mut set = SymbolSet::default();
        for (value, constraint) in self.iter() {
            if let Some(value) = value {
                set.insert_set(value.fv());
            }
            for value in constraint.keys().flatten() {
                set.insert_set(value.fv())
            }
        }
        set
    }
}

impl Hash for Consistent {
    fn hash<H: Hasher>(&self, hasher: &mut H) {
        self.code_array().hash(hasher)
    }
}

impl PartialEq for Consistent {
    fn eq(&self, other: &Consistent) -> bool {
        for (value, constraint) in self.iter() {
            if other.constraint(value) != constraint {
                return false;
            }
        }
        for (value, constraint) in other.iter() {
            if self.constraint(value) != constraint {
                return false;
            }
        }
        true
    }
}

impl Debug for Consistent {
    fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
        if let Some(set) = &self.0 {
            let mut printer = fmt.debug_map();
            for (value, constraint) in set.iter() {
                if let Some(value) = value {
                    printer.entry(value, constraint);
                } else {
                    printer.entry(&"self", constraint);
                }
            }
            printer.finish()
        } else {
            write!(fmt, "{{}}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn cycle_test() {
        let mut c = Consistent::new();
        let x = Some(SymbolId::param(FREE_LIFETIME.clone()).unwrap().into_valid());
        let y = Some(SymbolId::param(FREE_LIFETIME.clone()).unwrap().into_valid());
        let z = Some(SymbolId::param(FREE_LIFETIME.clone()).unwrap().into_valid());
        c.require(x.clone(), y.clone(), Relationship::LT, true)
            .unwrap();
        c.require(y.clone(), z.clone(), Relationship::LT, true)
            .unwrap();
        assert!(c
            .cycle_check(x.as_ref().unwrap(), |(value, _)| Some(value))
            .is_ok());
        assert!(c
            .cycle_check(y.as_ref().unwrap(), |(value, _)| Some(value))
            .is_ok());
        assert!(c
            .cycle_check(z.as_ref().unwrap(), |(value, _)| Some(value))
            .is_ok());
        c.require(z.clone(), x.clone(), Relationship::LT, true)
            .unwrap();
        assert!(c
            .cycle_check(x.as_ref().unwrap(), |(value, _)| Some(value))
            .is_err());
        assert!(c
            .cycle_check(y.as_ref().unwrap(), |(value, _)| Some(value))
            .is_err());
        assert!(c
            .cycle_check(z.as_ref().unwrap(), |(value, _)| Some(value))
            .is_err());
    }
}